import { app, BrowserWindow, ipcMain, screen } from 'electron'
import { createRequire } from 'node:module'
import { fileURLToPath } from 'node:url'
import path from 'node:path'

import axios from 'axios'
import fs from 'fs'
import os from 'os'
import { exec } from 'child_process'

const ENV = { win: os.type() == 'Windows_NT', mac: os.type() == 'Darwin', linux: os.type() == 'Linux', }


const require = createRequire(import.meta.url)
const __dirname = path.dirname(fileURLToPath(import.meta.url))

// The built directory structure
//
// ├─┬─┬ dist
// │ │ └── index.html
// │ │
// │ ├─┬ dist-electron
// │ │ ├── main.js
// │ │ └── preload.mjs
// │
process.env.APP_ROOT = path.join(__dirname, '..')

// 🚧 Use ['ENV_NAME'] avoid vite:define plugin - Vite@2.x
export const VITE_DEV_SERVER_URL = process.env['VITE_DEV_SERVER_URL']
export const MAIN_DIST = path.join(process.env.APP_ROOT, 'dist-electron')
export const RENDERER_DIST = path.join(process.env.APP_ROOT, 'dist')

process.env.VITE_PUBLIC = VITE_DEV_SERVER_URL ? path.join(process.env.APP_ROOT, 'public') : RENDERER_DIST

let win: BrowserWindow | null

function createWindow() {
  const { width, height } = screen.getPrimaryDisplay().workAreaSize;
  console.log('remote.', { width, height });
  win = new BrowserWindow({
    icon: path.join(process.env.VITE_PUBLIC, 'electron-vite.svg'),
    x: width * 0.2,
    y: height * 0.2,
    width: 1500 || width * 0.8,
    height: 800 || height * 0.8,
    //center: true,
    //fullscreen: true,
    autoHideMenuBar: true,
    webPreferences: {
      preload: path.join(__dirname, 'preload.mjs'),
    },
  })
  win.webContents.on('did-finish-load', () => {
    win?.webContents.send('main-process-message', (new Date).toLocaleString())
  })

  if (VITE_DEV_SERVER_URL) {
    win.loadURL(VITE_DEV_SERVER_URL)
  } else {
    win.loadFile(path.join(RENDERER_DIST, 'index.html'))
  }
  !app.isPackaged && win.webContents.openDevTools()
}

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
    win = null
  }
})

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})

app.whenReady().then(createWindow)


ipcMain.on('apply1', async (event, imageUrl) => {
  const userPath = app.getPath('home');
  const savePath = path.join(userPath, 'Downloads');
  if (!fs.existsSync(savePath)) fs.mkdirSync(savePath);
  const response = await axios({ url: imageUrl, responseType: 'stream', });
  const imageFileName = path.basename(imageUrl);
  const imagePath = path.join(savePath, imageFileName.replaceAll(" ", ''));
  console.log('apply1', imagePath);
  response.data.pipe(fs.createWriteStream(imagePath));

  response.data.on('end', () => {
    event.sender.send('apply1-end', imagePath);
    var cli;
    function flush(str) {
      for (let i = 0; i < 10; i++) {
        setTimeout(() => { exec(str, (error, stdout, stderr) => { }); }, i * 1000)
      }
    }
    if (ENV.win) {
      cli = `REG ADD "HKEY_CURRENT_USER\\Control Panel\\Desktop" /v Wallpaper /t REG_SZ /d "${imagePath.replaceAll("\\", "/")}" /f`
      return exec(cli, (error, stdout, stderr) => {
        flush(`REG ADD "HKCU\\Control Panel\\Desktop" /v WallpaperStyle /t REG_SZ /d 2 /f`);
        flush(`REG ADD "HKCU\\Control Panel\\Desktop" /v TileWallpaper /t REG_SZ /d 0 /f`);
        flush("RUNDLL32.EXE USER32.DLL,UpdatePerUserSystemParameters ,1 ,True")
      });
    }
    if (ENV.mac) {
      cli = `osascript -e 'tell application "Finder" to set desktop picture to POSIX file "${imagePath.replaceAll("\\", "/")}"'`
      return flush(cli)
    }

  });
})
// 这段只能给mac 用 win换图标是写注册表
ipcMain.on('apply2', async (event, obj) => {
  try {
    console.log('apply2', obj);
    var { url, name } = obj
    const userPath = app.getPath('home');
    const savePath = path.join(userPath, 'Downloads');
    if (!fs.existsSync(savePath)) fs.mkdirSync(savePath);
    const response = await axios({ url, responseType: 'stream', });
    const imageFileName = path.basename(url);
    const imagePath = path.join(savePath, imageFileName.replaceAll(" ", ''));
    console.log('apply1', imagePath);
    response.data.pipe(fs.createWriteStream(imagePath));
    var plist = `/Applications/${name}/Contents/Info.plist`
    const data = fs.readFileSync(plist, 'utf8');  
    const pattern = /<key>CFBundleIconFile<\/key>\s*<string>(.*?)<\/string>/;
    const match = data.match(pattern);
    if (match) { 
      var allpath = `/Applications/${name}/Contents/Resources/${match[1]}` 
      console.log(' allpath',  allpath); 
    }
    response.data.on('end', () => {
       exec(`cp ${imagePath}  ${allpath}`, (error, stdout, stderr) => { 
        console.log('error 2', error);
        exec(`touch /Applications/${name}`, (error, stdout, stderr) => { 
          
        });
       });
    })
  } catch (err) {
    console.error(err);
  }
})